package lucasapp.CentralStation_PRO;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;


/**
 * NtpClient - an NTP client for Java.  This program connects to an NTP server
 * and prints the response to the console.
 * 
 * The local clock offset calculation is implemented according to the SNTP
 * algorithm specified in RFC 2030.  
 * 
 * Note that on windows platforms, the curent time-of-day timestamp is limited
 * to an resolution of 10ms and adversely affects the accuracy of the results.
 * 
 */
public class SntpClient
{
	public static float OffsetOrologioLocale() throws Exception{
		String serverName = "pool.ntp.org"; 			//indirizzo automatico che seleziona il server adatto
		DatagramSocket socket = new DatagramSocket();	// Send request
		InetAddress address = InetAddress.getByName(serverName);
		byte[] buf = new NtpMessage().toByteArray();
		DatagramPacket packet =	new DatagramPacket(buf, buf.length, address, 123);
		// Set the transmit timestamp *just* before sending the packet
		NtpMessage.encodeTimestamp(packet.getData(), 40,(System.currentTimeMillis()/1000.0) + 2208988800.0);
		socket.send(packet);
		packet = new DatagramPacket(buf, buf.length);	// Get response
		socket.receive(packet);
		// Immediately record the incoming timestamp
		double destinationTimestamp = (System.currentTimeMillis()/1000.0) + 2208988800.0;
		NtpMessage msg = new NtpMessage(packet.getData());	// Process response
		// Corrected, according to RFC2030 errata
		//double roundTripDelay = (destinationTimestamp-msg.originateTimestamp) - (msg.transmitTimestamp-msg.receiveTimestamp);
		float localClockOffset = (float) (((msg.receiveTimestamp - msg.originateTimestamp)+(msg.transmitTimestamp - destinationTimestamp))/2)*1000;
		//System.out.println("Dest. timestamp:     " + NtpMessage.timestampToString(destinationTimestamp));
		//System.out.println("Local clock offset: " +	new DecimalFormat("0.00").format(localClockOffset*1000) + " ms");
		socket.close();
		return (localClockOffset);
	}
	
}
